<?php
namespace Home\Controller;
use Think\Crypt;
class UserController extends CommonController {

		//处理用户注册操作
		public function reg(){
			$member=D('member');
			if(IS_POST){
				$_POST['regtime']=time();
				$_POST['mail_str']=md5(uniqid());
				$_POST['password']=md5($_POST['password']);
				if($member->create()){
					$username=$member->username;
					$password=$member->password;
					if($member->add()){
						$member->username=$username;
						$member->password=$password;
						$member->login();
						$this->success('注册会员成功',U('index/index'));
					}else{
						$this->error('注册会员失败');
					}
				}else{
					$this->error($member->getError());
				}
				return;
			}
			$this->display();
		}
		
		//验证码图片
		public function verify(){
		
				$Verify = new \Think\Verify();
				$Verify->length   = 4;
				$Verify->entry();
		
	}
	
	
	
	//处理注册用户邮箱验证
	public function check_email(){
		$member=D('member');
		$data=$member->where(array('mail_str'=>I('es')))->field('id')->find();
		if($data){
			$member->where(array('id'=>$data['id']))->setField('check_mail',1);
			$member->where(array('id'=>$data['id']))->setField('mail_str','');
			$this->success('验证邮箱成功！',U('index/index'));
		}else{
			$this->success('验证邮箱失败！',U('reg'));
		}
	}
	
	
	//处理用户登录操作
	public function Login(){
		if(IS_POST){
			$member=D('member');
			if($member->create($_POST,4)){
				$res=$member->login();
				if($res){
					$returnURL=session('returnURL');
					if($returnURL){
						session('returnURL',null);
						$this->success("登录成功，正在跳转",U($returnURL));
					}else{
						$this->success("登录成功，正在跳转",U("index/index"));
					}
					exit;
				}else{
					$this->error("登录失败，用户名或密码错误");
				}
			}else{
				$this->error($member->getError());
			}
			return;
		}
		
		$this->display();
	}
	
	//判断用户是登录，如果sessiona里有值，则返回用户名及用户id
	public function checklogin(){
		$userid=session('id');
		if($userid){
			echo json_encode(array(
				'userid'=>$userid,
				'username'=>session('username'),
			));
		}else{
			if(isset($_COOKIE['username']) && isset($_COOKIE['password'])){
				$des_key=C('DES_KEY');
				$member=D('member');
				$member->username=trim(Crypt::decrypt($_COOKIE['username'],$des_key));
				$member->password=trim(Crypt::decrypt($_COOKIE['password'],$des_key));
				if($member->login()==true){
						echo json_encode(array(
					'userid'=>session('id'),
					'username'=>$member->username,
					));
				}
				
				
			}else{
				
			}
		}
	}
	
//处理用户退出功能
	public function logout(){
		$member=D('member');
		$member->logout();
		setcookie('username','',time()-1,'/');
			setcookie('password','',time()-1,'/');
		$this->success('退出成功',U('user/login'));
		
	}
	
	public function ceshi(){
		$des_key=C('DES_KEY');
		$a='abcdefg';
		$b=Crypt::encrypt($a,$des_key);
		echo $b."</br>";
		$c=Crypt::decrypt($b,$des_key);
		echo $c."</br>";
		echo $des_key;
	}
	
}